package com.mk.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mk.common.CommonUtils;
import com.mk.common.ThreadLocalUtil;
import com.mk.contants.UserConstant;
import com.mk.exception.BusinessException;
import com.mk.exception.ErrorCode;
import com.mk.exception.ThrowUtils;
import com.mk.mapper.UserMapper;
import com.mk.model.dto.user.UserAddRequest;
import com.mk.model.dto.user.UserQueryRequest;
import com.mk.model.entity.User;
import com.mk.model.enums.UserRoleEnum;
import com.mk.model.vo.user.LoginUserVO;
import com.mk.model.vo.user.UserVO;
import com.mk.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.mk.contants.UserConstant.DEFAULT_PASSWORD;
import static com.mk.contants.UserConstant.USER_LOGIN_STATE;

/**
* @author zkm
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-12-11 15:16:50
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword) {
        // TODO valid参数校验
        // 1. 参数校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册请求参数为空");
        this.checkUserAccountAndPassword(userAccount, userPassword);
        if (!userPassword.trim().equals(checkPassword.trim()))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
        // 2. 判断用户账号是否重复
        if (userByAccount(userAccount) != null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该账号已存在");
        if (getDelUserByAccount(userAccount) != null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复，该账号已被禁用！");
        // 3. 封装用户信息，执行添加
        String password = CommonUtils.getEncryptPassword(userPassword);
        // TODO 添加公共字段统一填充
        User user = User.builder()
                .userAccount(userAccount)
                .userPassword(password)
                .userNick("默认昵称")
                .userRole(UserRoleEnum.USER.getValue())
                .build();
         if (!this.save(user))
             throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败！");
        return user.getId();
    }

    @Override
    public Long userAdd(UserAddRequest userAddRequest) {
        // 1. 参数校验
        if (userAddRequest == null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        String userAccount  = userAddRequest.getUserAccount();
        this.checkUserAccountAndPassword(userAccount, DEFAULT_PASSWORD);
        User user = User.builder().build();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String encryptPassword = CommonUtils.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        // 默认权限
        if (StrUtil.isBlank(user.getUserRole()))
            user.setUserRole(UserConstant.DEFAULT_ROLE);
        // 2. 判断用户账号是否重复
        if (userByAccount(userAccount) != null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该账号已存在");
        // 3. 封装用户信息，执行添加
        if (!this.save(user))
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加失败！");
        return user.getId();
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 参数校验
        if (StrUtil.hasBlank(userAccount, userPassword))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登录请求参数为空");
        this.checkUserAccountAndPassword(userAccount, userPassword);
        // 2. 判断用户是否存在
        User user = userByAccount(userAccount); // 获取用户
        if (user == null)
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户账号不存在");
        // 3. 判断密码是否正确
        String loginPassword = CommonUtils.getEncryptPassword(userPassword);
        String password = user.getUserPassword();
        if (!loginPassword.equals(password))
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "输入账号或密码错误");
        // 4. 用户脱敏
        LoginUserVO loginUserVO = this.getLoginUserVO(user);
        // 5. 存储用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return loginUserVO;
    }

    // TODO 通过ThreadLocal存储登录用户信息
    @Override
    public LoginUserVO getCurrentLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        Long userId = currentUser.getId();
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return this.getLoginUserVO(user);
    }

    @Override
    public User getCurrentLoginUser() {
        User loginUser = ThreadLocalUtil.get(USER_LOGIN_STATE);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        return loginUser;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null)
            return null;
        LoginUserVO userVO = LoginUserVO.builder().build();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        Object user = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null)
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userNick = userQueryRequest.getUserNick();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        Boolean isAsc = true == userQueryRequest.getIsAsc();

        QueryWrapper<User> queryWrapper = Wrappers.query();
        queryWrapper.eq(ObjUtil.isNotNull(id), User.Fields.ID, id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), User.Fields.USER_ROLE, userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), User.Fields.USER_ACCOUNT, userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userNick), User.Fields.USER_NICK, userNick);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), User.Fields.USER_PROFILE, userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), isAsc , sortField);
        return queryWrapper;
    }


    /**
     * 校验用户名密码是否合法
     * @param userAccount
     * @param userPassword
     */
    private void checkUserAccountAndPassword(String userAccount, String userPassword){
        if (userAccount.trim().length() < 4)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        if (userPassword.trim().length() < 8)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
    }

    /**
     * 通过用户账号查询用户
     * @param userAccount
     * @return 用户信息
     */
    private User userByAccount(String userAccount){
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUserAccount, userAccount.trim());
        User user = this.getOne(wrapper);
        return user != null ? user : null;
    }

    @Override
    public User getDelUserByAccount(String userAccount) {
        User delUser = userMapper.getDelUserByAccount(userAccount);
        return delUser != null ? delUser : null;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserConstant.ADMIN_ROLE.equals(user.getUserRole());
    }
}




